package com.silence.dao.impl;

import com.silence.dao.IUserDao;
import com.silence.model.User;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @author Silence
 */
@Repository("jdbcUserDao")
public class UserDao implements IUserDao {

    private JdbcTemplate jdbcTemplate;

    @Resource
    public void setJdbcTemplate(DataSource dataSource){
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    @Override
    public void add(User user) {
        String sql = "INSERT INTO t_user(username, password) VALUES (?,?)";
        Object[] args = new Object[]{user.getUsername(), user.getPassword()};
        this.jdbcTemplate.update(sql, args);
    }

    @Override
    public void update(User user) {
        String sql = "UPDATE t_user SET username = ?, password = ? WHERE id = ?";
        Object[] args = new Object[]{user.getUsername(), user.getPassword(), user.getId()};
        this.jdbcTemplate.update(sql, args);
    }

    @Override
    public void delete(Integer id) {
        String sql = "DELETE FROM t_user WHERE id = ?";
        Object[] args = new Object[]{id};
        this.jdbcTemplate.update(sql, args);
    }

    @Override
    public User selectById(Integer id) {
        String sql = "SELECT * FROM t_user WHERE id = ?";
        Object[] args = new Object[]{id};
        return this.jdbcTemplate.queryForObject(sql, args, new UserMapper());
    }

    @Override
    public List<User> selectAll() {
        String sql = "SELECT * FROM t_user";
        return this.jdbcTemplate.query(sql, new UserMapper());
    }

    class UserMapper implements RowMapper<User>{

        @Override
        public User mapRow(ResultSet rs, int rowNum) throws SQLException {
            User user = new User();
            user.setId(rs.getInt(1));
            user.setUsername(rs.getString(2));
            user.setPassword(rs.getString(3));
            return user;
        }
    }
}
